<template>
  <div id="app">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div id="pdfDom">
      <div class="background">
        <div class="certificate-content">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{stuName}}学员</div>
        <div class="certificate-desc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;恭喜您在{{stageNum}}{{courseName}}课程学习中，高效完成各项学习目标与考核，成绩优异，特颁发此证书，以资鼓励！</div>
        <div class="company-name">中煤平朔集团有限公司</div>
        <div class="certificate-date">{{formatDate(createTime)}}</div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    name: "",
    props: {
      rowData: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        but: true,
        resultImgurl: '',
        isLoading: false,
        stuName: '张三',
        stageNum: '2025期',
        courseName: '一通三防',
        issueTimeYear: '2025',
        issueTimeMouth: '09',
        issueTimeDay: '10',
        createTime: '2025-09-10 00:00:00',
      }
    },
    watch: {
      // 监听rowData变化，更新组件数据
      rowData: {
        immediate: true, // 立即执行一次
        handler(newVal) {
          console.log("接收到数据:", newVal); // 修改日志信息
          if (newVal) {
            // 根据实际数据结构调整以下赋值
            this.stuName = newVal.stuName || '学员姓名';
            this.courseName = newVal.courseName || '课程名称';
            this.stageNum = newVal.stageNum || '期数';
            this.createTime = newVal.createTime || new Date().toISOString();
          }
        }
      }
    },
    mounted() {
      console.log("子组件已挂载，当前props:", this.rowData);
      // 组件挂载时也尝试更新数据
      if (this.rowData) {
        this.stuName = this.rowData.stuName || '学员姓名';
        this.courseName = this.rowData.courseName || '课程名称';
        this.stageNum = this.rowData.stageNum || '期数';
        this.createTime = this.rowData.createTime || new Date().toISOString();
      }
    },
    methods: {
      formatDate(dateString) {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '无效日期';

        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();

        return `${year}年${month}月${day}日`;
      },
      // 导出为pdf
      exportPDF() {
        this.savePDF()
                .then((blob) => {
                  const blobUrl = URL.createObjectURL(blob);

                  // 先预览
                  const previewWindow = window.open(blobUrl, '_blank');

                  // 自动下载
                  const fileName = `荣誉证书.pdf`;
                  const downloadLink = document.createElement('a');
                  downloadLink.href = blobUrl;
                  downloadLink.download = fileName;
                  document.body.appendChild(downloadLink);
                  downloadLink.click();
                  document.body.removeChild(downloadLink);

                  // 监听预览窗口关闭后释放内存
                  if (previewWindow) {
                    const timer = setInterval(() => {
                      if (previewWindow.closed) {
                        clearInterval(timer);
                        URL.revokeObjectURL(blobUrl);
                      }
                    }, 1000);
                  } else {
                    setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
                  }
                })
                .catch(error => {
                  console.error('导出PDF出错:', error);
                  alert('导出失败，请重试或联系管理员');
                });
      },
      savePDF() {
        return new Promise((resolve, reject) => {
          this.$nextTick(() => {
            import('html2pdf.js').then((module) => {
              const html2pdf = module.default;

              // 配置选项
              const opt = {
                margin: 0,
                image: {
                  type: 'jpeg',
                  quality: 0.98
                },
                html2canvas: {
                  scale: 2,
                  logging: false,
                  useCORS: true
                },
                jsPDF: {
                  unit: 'mm',
                  format: 'a4',
                  orientation: 'portrait'
                }
              };

              const element = document.getElementById('pdfDom');

              // 生成PDF Blob对象
              html2pdf()
                      .set(opt)
                      .from(element)
                      .toPdf()
                      .get('pdf')
                      .then((pdf) => {
                        const blob = pdf.output('blob');

                        resolve(blob); // 返回Blob对象
                      })
                      .catch((error) => {
                        reject(error);
                      });
            }).catch((error) => {
              reject(error);
            });
          });
        });
      },
    }
  }
</script>

<style scoped>

  body {
    font-family: "Microsoft YaHei", sans-serif;
    margin: 0;
    padding: 20px;
    background-color: #f5f5f5;
  }

  .no-print {
    text-align: center;
    margin-bottom: 20px;
  }

  #pdfDom {
    margin: 0 auto;
    position: relative;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .background {
    background-image: url('../../assets/honor.jpg');
    width: 700px;
    height: 490px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
  }

  .certificate-content {
    position: absolute;
    top: 37%;
    left: 111px;
    right: 92px;
    font-size: 18px;
    color: #111;
  }

  .certificate-desc {
    position: absolute;
    top: 43%;
    left: 111px;
    right: 92px;
    font-size: 18px;
    color: #111;
    line-height: 1.6;
  }

  .company-name {
    position: absolute;
    top: 74%;
    left: 450px;
    font-size: 16px;
    color: #111;
  }

  .certificate-date {
    position: absolute;
    top: 78%;
    left: 475px;
    font-size: 16px;
    color: #111;
  }

  /* 打印样式 */
  @media print {
    @page {
      size: landscape; /* 设置为横向打印 */
      margin: 0; /* 去除页边距 */
    }

    body, html {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }

    .no-print {
      display: none !important;
    }

    #pdfDom {
      width: 100%;
      height: 100%;
      box-shadow: none;
      margin: 0;
      padding: 0;
    }
  }
</style>
